import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/controllers/fav_list_controller.dart';
import 'package:flutter_demo/entities/article_item.dart';
import 'package:get/get.dart';

import '../utils/const.dart';
import 'article_detail_page.dart';

class FavListPage extends StatelessWidget {
  const FavListPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Get.put(FavListController());
    return Scaffold(
      appBar: AppBar(
        title: const Text("我的收藏"),
        elevation: 0,
        toolbarHeight: Const.kAppBarHeight,
      ),
      body: GetBuilder<FavListController>(
        init: FavListController(),
        builder: (favC) => ListView.separated(
            itemBuilder: (_, index) {
              return _buildItem(favC.favList.val[index]);
            },
            separatorBuilder: (_, index) {
              return const Divider(
                height: 0.5,
              );
            },
            itemCount: favC.favList.val.length),
      ),
    );
  }

  Widget _buildItem(dynamic d) {
    final item = ArticleItem.fromJson(d);
    return InkWell(
      onTap: () => _handleToDetail(item),
      child: Padding(
        padding: const EdgeInsets.all(8),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.only(right: 5),
              child: CachedNetworkImage(
                imageUrl: item.cover.toString(),
                httpHeaders: Const.imgHeaders,
                width: 120,
                height: 65,
              ),
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    item.title,
                    style: const TextStyle(fontWeight: FontWeight.w500),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(6),
                    child: Row(
                      children: item.tags
                          .map(
                            (e) => Text(
                              e,
                              style: const TextStyle(fontSize: 12),
                              overflow: TextOverflow.clip,
                            ).paddingOnly(right: 10),
                          )
                          .toList(),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  _handleToDetail(ArticleItem item) {
    Get.to(() => ArticleDetailPage(), arguments: item);
  }
}
